<template>
  <page-header-wrapper>
    <a-card
      :bordered="false"
      title="权限配置">
      <a-row :gutter="24">
        <a-col :md="12">
          <a-spin :spinning="loading">
            <a-card title="角色">
              <div class="table-operator">
                <h2>当前角色：{{ selectRow.roleName }}</h2>
                <a-button
                  type="primary"
                  icon="plus"
                  v-if="save"
                  @click="handleAdd">新建</a-button>
              </div>
              <a-list
                item-layout="horizontal"
                :data-source="roloIdMap"
                :style="{height: '508px', overflow: 'scroll' }">
                <a-list-item
                  slot="renderItem"
                  slot-scope="item, index"
                  :id="index">
                  <a-list-item-meta>
                    <div slot="title">
                      <span
                        :style="{cursor: 'pointer'}"
                        @click="(e) => handleClick(item)">{{ item.roleName }}
                      </span>
                      <span :style="{float: 'right', marginRight: '20px'}">
                        <a v-if="deleteBtn" @click="(e) => handleDelete(item)">删除</a>
                        <!-- <a
                          :style="{marginLeft: '20px'}"
                          @click="(e) => handleEdit(item)">编辑</a> -->
                      </span>
                    </div>
                  </a-list-item-meta>
                </a-list-item>
              </a-list>
            </a-card>
          </a-spin>
        </a-col>
        <a-col :md="12">
          <a-card title="权限">
            <a-spin :spinning="loading">
              <a-tree
                v-if="menuTree"
                checkable
                :style="{height: '600px', overflow: 'scroll' }"
                :tree-data="menuTree"
                :defaultExpandAll="false"
                v-model="selectedKeys"
                :replaceFields="{value: 'menuId',title:'name', key: 'menuId'}" />
            </a-spin>
          </a-card>
          <a-button
            type="primary"
            :style="{marginTop: '30px'}"
            @click="handleEdit"
            v-if="selectRow.hasOwnProperty('roleName') && this.update">确认修改</a-button>
        </a-col>
      </a-row>
      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :menuTree="menuTree"
        @cancel="handleCancel"
        @ok="handleOk" />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { roleSelect, menuList, addRole, roleDelete, roleUpdate, roleMenu } from '@/api/manage'
import CreateForm from './modules/CreateForm'
import STree from '@/components/Tree/Tree'
import { message, Modal } from 'ant-design-vue'
import { dfsPath } from './until'
import { isInMenu } from '../config.js'
import { mapGetters } from 'vuex'

const listToTree = menuList => {
  menuList.forEach(element => {
    const parentId = element.parentId
    if (parentId !== 0) {
      menuList.forEach(ele => {
        if (ele.menuId === parentId) {
          // 当内层循环的ID== 外层循环的parendId时，（说明有children），需要往该内层id里建个children并push对应的数组；
          if (!ele.children) {
            ele.children = []
          }
          ele.children.push(element)
        }
      })
    }
  })
  menuList = menuList.filter(ele => ele.parentId === 0) // 这一步是过滤，按树展开，将多余的数组剔除；
  return menuList
}

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    STree
  },
  data () {
    return {
      // 权限参数
      info: false, // 查看联系人
      list: false, // 列表
      save: false, // 家
      select: false, // 查所有 基本没有
      deleteBtn: false, // 删
      update: false, // 改

      selectedKeys: [],
      selectRow: {},
      visible: false,
      roleName: undefined,
      confirmLoading: false,
      loading: true,
      // 高级搜索 展开/关闭
      advanced: false,
      halfCheckedKeys: undefined,
      // 查询参数
      queryParam: {},
      roloIdMap: undefined,
      menuList: undefined,
      menuMap: undefined,
      menuTree: undefined,
      // 加载数据方法 必须为 Promise 对象
      staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      physicalSurveyCurrRowId: null
    }
  },
  created () {
    // 点击查看
    this.list = isInMenu(this.menu, 'ROLE_but:role:select') && isInMenu(this.menu, 'ROLE_but:role:info')
    // 增加
    this.save = isInMenu(this.menu, 'ROLE_but:role:save') && isInMenu(this.menu, 'ROLE_but:menu:select')
    // 改
    this.update = isInMenu(this.menu, 'ROLE_but:role:update') && isInMenu(this.menu, 'ROLE_but:menu:select')
    // 删除
    this.deleteBtn = isInMenu(this.menu, 'ROLE_but:role:delete')
  },
  computed: {
    ...mapGetters(['menu']),
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  mounted () {
    this.loading = true
    isInMenu(this.menu, 'ROLE_but:role:select') && roleSelect()
      .then(res => {
        this.roloIdMap = res.data
        this.loading = false
      })
      .finally(() => {
        this.loading = false
      })
    this.list && menuList().then(res => {
      this.menuList = res.data
      this.menuTree = listToTree(this.menuList)

      const _map = new Map()
      this.menuList.forEach((menu, index) => {
        _map.set(menu.menuId, index)
      })
      this.menuMap = _map
    })
  },
  methods: {
    // onCheck (checkedKeys, info) {
    //   console.log('onCheck', checkedKeys, info.halfCheckedKeys)
    //   this.halfCheckedKeys = info.halfCheckedKeys
    // },
    handleEdit (record) {
      console.log(this.selectedKeys)
      const _menuIds = []
      this.selectedKeys.forEach(id => {
        const _path = dfsPath(id, this.menuList)
        _path.forEach(_id => _menuIds.push(_id))
      })
      const _menuIdSet = new Set(_menuIds)
      this.loading = true
      roleUpdate({
        roleName: this.selectRow.roleName,
        roleId: this.selectRow.roleId,
        menuIds: [..._menuIdSet].join(',')
      }).then(() => {
        roleSelect().then(() => {
          this.loading = false
          message.success('修改角色权限成功')
        })
      })
      // this.visible = true
      // menuIdList
    },
    handleDelete (record) {
      Modal.confirm({
        title: '删除角色',
        content: '删除后数据不再展示，需要查看请联系开发',
        onOk: () => {
          this.loading = true
          roleDelete({ roleId: record.roleId }).then(() => {
            roleSelect()
              .then(res => {
                this.roloIdMap = res.data
                message.success('删除成功')
              }).finally(() => {
                this.loading = false
              })
          })
        }
      })
    },
    handleClick (record) {
      this.selectRow = record
      // this.menuMap
      const _keys = []
      this.loading = true
       this.list && roleMenu(record.roleId)
        .then(res => {
          res.data.menuIdList.forEach((id, ind) => {
            const index = this.menuMap.get(id)
            const item = this.menuList[index]
            if (item.type === 2) {
              _keys.push(id)
            }
          })
          this.selectedKeys = _keys
          console.log('this.selectedKeys', this.selectedKeys, this.menuMap)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleAdd () {
      this.visible = true
    },
    handleOk () {
      const form = this.$refs.createModal.form
      // form.get('')
      form.validateFields((errors, values) => {
        if (!errors) {
          // console.log('values', values)
          const _menuIds = []
          values.menuIdList.forEach(id => {
            const _path = dfsPath(id, this.menuList)
            _path.forEach(_id => _menuIds.push(_id))
          })
          const _menuIdSet = new Set(_menuIds)
          const params = Object.assign({}, values, { menuIds: [..._menuIdSet].join(','), menuIdList: undefined })
          this.confirmLoading = true
          addRole(params)
            .then(res => {
              this.confirmLoading = false
              this.visible = false
              // 重置表单数据
              form.resetFields()
              this.$message.success('新增成功')
              this.loading = true
              roleSelect()
                .then(res => {
                  this.roloIdMap = res.data
                  this.loading = false
                })
                .finally(() => {
                  this.loading = false
                })
            })
            // eslint-disable-next-line handle-callback-err
            .catch(err => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.ant-list-item-meta-title {
  color: red;
}
</style>
